package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    public static final String TOKEN = "https://api.weixin.qq.com/cgi-bin/token";
    public static final String PHONE = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String secret;
    @Override
    public String getOpenid(String code) {
        Map<String,Object> map = new HashMap<>();
        map.put("appid", appid);
        map.put("secret", secret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String ss = HttpUtil.get(WX_LOGIN, map);
        JSONObject entries = JSONUtil.parseObj(ss);
        // 判断接口响应是否出错
        if(ObjectUtil.isNotEmpty(entries.getInt("errcode"))) {
            throw new RuntimeException(entries.getStr("errmsg"));
        }
        return entries.getStr("openid");
    }

    public String getToken(){
        Map<String,Object> map = new HashMap<>();
        map.put("grant_type", "client_credential");
        map.put("appid", appid);
        map.put("secret", secret);
        String s = HttpUtil.get(TOKEN, map);
        JSONObject entries = JSONUtil.parseObj(s);
        if(ObjectUtil.isNotEmpty(entries.getInt("errcode"))) {
            throw new RuntimeException(entries.getStr("errmsg"));
        }
        return entries.getStr("access_token");
    }

    @Override
    public String getPhone(String detailCode) {
        String url = PHONE + getToken();
        Map<String,Object> map = new HashMap<>();
        map.put("code", detailCode);
        String s = HttpUtil.post(url,JSONUtil.toJsonStr(map));
        JSONObject entries = JSONUtil.parseObj(s);
        // 判断接口响应是否出错
        if(entries.getInt("errcode") != 0) {
            throw new RuntimeException(entries.getStr("errmsg"));
        }
        return entries.getJSONObject("phone_info").getStr("phoneNumber");
    }

}
